#!/usr/local/bin/python
# Rob Dennis - Lurchington Q. Delacroix
# Keasby - TV renamer
# Project Homepage: http://code.google.com/p/keasby/

#--- Python Imports
import sys
import os
import unittest
import logging
from optparse import OptionParser

#--- Keasby Imports
from keasby_config_parser import KeasbyConfigParser

log = logging.getLogger("keasby_logger")

class KeasbyOptions(object):
    """
    Handles all options for the Keasby Application
    """

    def __init__(self):

        self.parser = OptionParser(version="%prog - 1.0 - IRAD")

        self._populate_options()

#--- Specify defaults

        self._set_defaults()
        config_path=os.path.join("preferences.cfg")
        self._set_defaults_from_file(config_path)

        (self.cl_opts, self.cl_args) = self.parser.parse_args()

    def _populate_options(self):
        """
        populates the options parsed from the command-line, including help info
        """
        self.parser.add_option( "-p", "--pretend",
                                dest="pretend", action="store_true",
                                help="do not make any changes \
                                [default: %default]")

        self.parser.add_option( "-P", "--noPretend", dest="pretend",
                                action="store_false",
                                help="make changes as necessary")

        self.parser.add_option( "-a", "--assumeGroupedNum",
                                dest="assume_grouped_numbers",
                                action="store_true",
                                help="treats fields like 1005 as both season \
                                and episode number [default: %default]")

        self.parser.add_option( "-A", "--noAssumeGroupedNum",
                                dest="assume_grouped_numbers",
                                action="store_false",
                                help="treats fields like 1005 as one number")

        self.parser.add_option( "-g", "--groupedNumSplit",
                                dest="grouped_num_split",
                                metavar="NUM", type="int",
                                help="when handling group numbers, split \
                                after NUM places [default: %default]")

        self.parser.add_option( "-G", "--episodePadding",
                                dest="episode_padding", metavar="NUM",
                                type="int",
                                help="pads episode number to NUM places \
                                [default: %default]")

        self.parser.add_option( "--seasonPadding", dest="season_padding",
                                metavar="NUM", type="int",
                                help="pads season number to NUM places \
                                [default: %default]")

        self.parser.add_option( "--splitEpisodeChar", dest="split_episode_char",
                                metavar="CHAR",
                                help="Detects numbers split by CHAR as \
                                multi-episodic [default: %default]")

        self.parser.add_option( "-r", "--recursiveRename",
                                dest="recursive_rename", action="store_true",
                                help="recursively rename files in all \
                                subdirectory [default: %default]")

        self.parser.add_option( "-R", "--noRecursiveRename",
                                dest="recursive_rename", action="store_false",
                                help="limit renaming to current directory")

        self.parser.add_option( "-d", "--debug",
                                dest="debug", action="store_true",
                                help="print extra debug output \
                                [default: %default]")

        self.parser.add_option( "-D", "--noDebug",
                                dest="debug", action="store_false",
                                help="do not print extra debug output")

        self.parser.add_option( "-v", "--verbose", dest="verbose",
                                action="store_true",
                                help="print verbose output \
                                [default: %default]")

        self.parser.add_option( "-V", "--noVerbose",
                                dest="verbose", action="store_false",
                                help="do not print verbose output")

        self.parser.add_option( "-q", "--quiet",
                                dest="show_output", action="store_false",
                                help="squelch all output except errors \
                                [default: %default]")

        self.parser.add_option( "-Q", "--noQuiet",
                                dest="show_output", action="store_true",
                                help="print output as normal")

        self.parser.add_option( "-t", "--topLevel",
                                dest="input_dir", metavar="PATH",
                                help="top level source hierarchy \
                                [default: current working directory]")

        self.parser.add_option( "-T", "--topLevelOutput",
                                dest="output_dir", metavar="PATH",
                                help="top level destination hierarchy \
                                [default: current working directory]")

        self.parser.add_option( "--cacheDirectory",
                                dest="cache_dir", metavar="PATH",
                                help="location of cache directory \
                                [default: %default]")

        self.parser.add_option( "-f", "--writeToFolder",
                                dest="write_to_folder", action="store_true",
                                help="enables writing renamed files to \
                                folders, instead of in place \
                                [default: %default]")

        self.parser.add_option( "-F", "--noWriteToFolder",
                                dest="write_to_folder", action="store_false",
                                help="disables writing renamed files \
                                to new folder, just within current folder")

        self.parser.add_option( "--unattended",
                                dest="unattended", action="store_true",
                                help="do not prompt for input \
                                [default: %default]")

        self.parser.add_option( "--interactive",
                                dest="unattended", action="store_false",
                                help="require prompts for input")

        self.parser.add_option( "-o", "--outputNameString",
                                dest="output_template", metavar="STRING",
                                help="rename filename to formatted STRING \
                                [default: %default]")

        self.parser.add_option( "--showname", dest="manual_showname",
                                help="manually specify the showname \
                                to use [default: %default]")

        self.parser.add_option( "--season", dest="manual_season",
                                help="manually specify the season \
                                to use [default: %default]")

    def _set_defaults(self):
        """
        Specify default values for specific options
        """

        _tmp_dict = {"epnum":"${episode_number}",
                         "season":"${season_number}",
                         "show":"${showname}",
                         "title":"${episode_title}"
                        }

        _template_file = "%(show)s-S%(season)sE%(epnum)s-%(title)s"%_tmp_dict

        _rename_template = os.path.join("${showname}",
                                       "Season ${season_number}",
                                       _template_file)

        self.parser.set_defaults(
                                undo_batch = False,
                                name_batch = False,
                                flush_cache_to_disk = False,
                                overwrite_batch = True,
                                pretend = False,
                                guess_multipart = True,
                                handle_absolute_ordering = False,
                                assume_grouped_numbers = True,
                                grouped_num_split = 2,
                                episode_padding = 2,
                                season_padding = 2,
                                split_episode_char = "-",
                                replace_whitespace = True,
                                allow_partial_info = True,
                                recursive_rename = True,
                                debug = False,
                                verbose = False,
                                show_output = True,
                                cache_dir = os.path.join(sys.path[0], "cache"),
                                input_dir = os.getcwd(),
                                output_dir = os.getcwd(),
                                write_to_folder = False,
                                unattended = False,
                                output_template = _rename_template,
                                manual_showname = None,
                                manual_season = None
                                )

    def _set_defaults_from_file(self, filename):
        """
        Specify default values using a config file
        """

        pref_config = KeasbyConfigParser()
        pref_config.read(filename)

        for key, value in pref_config.yield_dict_items():
            log.debug("%s = %s (%s)"%(key,value,type(value)))

            try:
                # hack to have the string represented by variable key,
                # not be read as the string "key"
                self.parser.set_defaults(**{key:value})
            except Exception as detail:
                raise KeasbyConfigError(detail)

class KeasbyOptionsError(Exception):
    """
    Generic KeasbyOptionsError
    """
    pass


#--- Global instance of options class
kopt = KeasbyOptions()


if __name__ == "__main__":
    pass